//
//  DDropNoteViewController.swift
//  Drop
//
//  Created by hushaohua on 2018/6/6.
//  Copyright © 2018年 init. All rights reserved.
//

import UIKit

class DDropNoteViewController: UIViewController, UITextViewDelegate {

    override func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
        if (self.contentView.bounds.contains(touch.location(in: self.contentView))){
            return false;
        }
        return true;
    }
    
    @objc override func dismissKeyboard(){
        super.dismissKeyboard();
        self.dismiss(animated: false, completion: nil);
    }
    
    var drop:Drop?;
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        self.view.backgroundColor = UIColor(white: 0.3, alpha: 0.5);
        self.addKeyboardObserver();
        
        self.view.addSubview(self.contentView);
        self.view.addSubview(self.noteTextView);
        self.view.addSubview(self.tagLabel);
        self.view.addSubview(self.beginDateLabel);
        self.view.addSubview(self.enDateLabel);
        
        self.enableTapToDismissKeyboard();
        if (self.drop != nil){
            self.noteTextView.text = self.drop?.note;
            self.tagLabel.text = self.drop!.tag!.name;
            let dateFormatter = DateFormatter();
            dateFormatter.dateFormat = "HH:mm";
            self.enDateLabel.text = dateFormatter.string(from: self.drop!.end! as Date);
            self.beginDateLabel.text = dateFormatter.string(from: self.drop!.begin! as Date);
            self.layoutToSource();
        }
    }
    
    func gotoAdjust() {
        if (self.isAppeared){
            self.noteTextView.becomeFirstResponder();
        }
    }
    
    var isAppeared:Bool = false;
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated);
        self.isAppeared = true;
        if (!self.noteTextView.isFirstResponder){
            self.noteTextView.becomeFirstResponder();
        }
    }

    lazy var contentView:UIView = {
        var view:UIView = UIView(frame: CGRect(x:10,y:100,width:self.view.bounds.size.width - 20,height:80));
        view.backgroundColor = UIColor.white;
        view.layer.cornerRadius = 3;
        view.layer.masksToBounds = true;
        return view;
    }();
    
    var sourceTagFrame:CGRect?;
    lazy var tagLabel:UILabel = {
        var label:UILabel = UILabel(frame: CGRect(x:20,y:0,width:self.view.bounds.width - 40,height:32));
        label.textColor = UIColor.darkGray;
        label.font = UIFont.systemFont(ofSize: 16, weight: .regular);
        label.textAlignment = .center;
        label.numberOfLines = 2;
        return label;
    }();
    
    var sourceBeginDateFrame:CGRect?;
    lazy var beginDateLabel:UILabel = {
        var label:UILabel = UILabel(frame: CGRect(x:20,y:0,width:self.view.bounds.width - 40,height:32));
        label.textColor = UIColor.gray;
        label.font = UIFont.systemFont(ofSize: 16, weight: .thin);
        label.textAlignment = .left;
        return label;
    }();
    var sourceEndDateFrame:CGRect?;
    lazy var enDateLabel:UILabel = {
        var label:UILabel = UILabel(frame: CGRect(x:20,y:0,width:self.view.bounds.width - 40,height:32));
        label.textColor = UIColor.gray;
        label.font = UIFont.systemFont(ofSize: 16, weight: .thin);
        label.textAlignment = .right;
        return label;
    }();
    
    
    lazy var noteTextView:UITextView = {
        var textView = UITextView(frame: .zero, textContainer: nil);
        textView.textContainer.maximumNumberOfLines = 2;
        textView.delegate = self;
        textView.font = UIFont.systemFont(ofSize: 14, weight:.light);
        textView.layer.cornerRadius = 2;
        textView.layer.masksToBounds = true;
        textView.backgroundColor = UIColor(white: 0.90, alpha: 0.95);
        textView.returnKeyType = .done;
        return textView;
    }();
    
    var didUpdateDropNote:(()->Void)?;
    func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
        if (textView.markedTextRange == nil){
            if (text == "\n"){
                self.drop?.note = textView.text;
                self.drop?.hideNote = textView.text.count == 0;
                HStoreManager.defaultManger().saveContext();
                if (self.didUpdateDropNote != nil){
                    self.didUpdateDropNote!();
                }
                self.dismissKeyboard();
                return false;
            }
            return true;
        }
        return true;
    }
    
    func addKeyboardObserver() -> Void {
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillChangeFrame(_:)), name: Notification.Name.UIKeyboardWillChangeFrame, object: nil);
    }
    
    func removeKeyboardObserver() -> Void {
        NotificationCenter.default.removeObserver(self, name: Notification.Name.UIKeyboardWillShow, object: nil);
        NotificationCenter.default.removeObserver(self, name: Notification.Name.UIKeyboardWillHide, object: nil);
    }
    
    func printKeyboard(_ notification:NSNotification){
        let endFrame:CGRect = notification.userInfo![UIKeyboardFrameEndUserInfoKey] as! CGRect;
        let beginFrame:CGRect = notification.userInfo![UIKeyboardFrameBeginUserInfoKey] as! CGRect;
        print("keyboard----begin:\(beginFrame), end:\(endFrame)")
    }
    
    func layoutToSource() {
        self.tagLabel.frame = self.sourceTagFrame!;
        self.contentView.frame = self.sourceTagFrame!;
        self.noteTextView.frame = self.sourceTagFrame!;
        self.beginDateLabel.frame = self.sourceBeginDateFrame!;
        self.enDateLabel.frame = self.sourceEndDateFrame!;
    }
    
    func layoutToDest(_ keyboardFrame:CGRect) {
        self.noteTextView.frame.size.height = 44;
        let adjustY = keyboardFrame.origin.y - 15 - 44 - 30;
        if (adjustY < self.noteTextView.frame.origin.y){
            self.noteTextView.frame.origin.y = adjustY;
        }
        
        self.tagLabel.frame.origin.x = 5;
        self.tagLabel.frame.origin.y = self.noteTextView.frame.origin.y;
        self.tagLabel.frame.size.width = self.noteTextView.frame.origin.x - 10;
        self.tagLabel.frame.size.height = 44;
        
        self.beginDateLabel.frame.origin.x = self.noteTextView.frame.origin.x;
        self.beginDateLabel.frame.size.height = 30;
        self.beginDateLabel.frame.origin.y = self.tagLabel.frame.origin.y - self.beginDateLabel.frame.size.height;
        self.beginDateLabel.frame.size.width = 55;
        
        self.enDateLabel.frame.origin.x = self.noteTextView.frame.maxX - 55;
        self.enDateLabel.frame.origin.y = self.beginDateLabel.frame.origin.y;
        self.enDateLabel.frame.size.width = 55;
        self.enDateLabel.frame.size.height = 30;
        
        self.contentView.frame.origin.x = 5;
        self.contentView.frame.origin.y = self.beginDateLabel.frame.origin.y;
        self.contentView.frame.size.width = self.view.bounds.size.width - 10;
        self.contentView.frame.size.height = self.noteTextView.frame.size.height + 30 + 15;
    }
    
    @objc func keyboardWillChangeFrame(_ notification:NSNotification){
        let endFrame:CGRect = notification.userInfo![UIKeyboardFrameEndUserInfoKey] as! CGRect;
        let beginFrame:CGRect = notification.userInfo![UIKeyboardFrameBeginUserInfoKey] as! CGRect;
        let duration:TimeInterval = notification.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! TimeInterval;
        let curve:Int = notification.userInfo![UIKeyboardAnimationCurveUserInfoKey] as! Int;
        let option:UIViewAnimationOptions = UIViewAnimationOptions(rawValue: UInt(curve));
        print("change----begin:\(beginFrame), end:\(endFrame)")
        let beginY = Int(beginFrame.origin.y);
        let endY = Int(endFrame.origin.y);
        let screenHeight = Int(UIScreen.main.bounds.size.height);
        UIView.animate(withDuration: duration, delay: 0, options: option, animations: {
            if (beginY == screenHeight){
                self.layoutToDest(endFrame);
            }else if (endY == screenHeight){
                self.layoutToSource();
            }else{
                self.layoutToDest(endFrame);
            }
        }) { (finished) in

        }
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}
